package com.citasgoo.aliyunFacility.util;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.citasgoo.aliyunFacility.api.AliyunKey;
import com.citasgoo.aliyunFacility.api.SmsEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class AliyunSmsUtil {

    private final static Logger logger = LoggerFactory.getLogger(AliyunSmsUtil.class);

    public static final String PHONE = "PHONE";

    public static final String SMS_CODE = "SMS_CODE";

    public static String sendSms(SmsEntity smsEntity) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", AliyunKey.getAccessKeyId(), AliyunKey.getAccessSecret());
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", smsEntity.getPhoneNumbers());
        request.putQueryParameter("SignName", AliyunKey.getSignName());
        request.putQueryParameter("TemplateCode", smsEntity.getSmsCode());
        Object json = JSONObject.toJSON(smsEntity.getParam());
        request.putQueryParameter("TemplateParam", json.toString());
        try {
            CommonResponse response = client.getCommonResponse(request);
            return response.getData();
        } catch (ServerException e) {
            e.printStackTrace();
            return "{'Code':'failed','Message':'其他错误'}";
        } catch (ClientException e) {
            e.printStackTrace();
            return "{'Code':'failed','Message':'其他错误'}";
        }
    }


    public static  String sendSms(Map<String,String> param){
        SmsEntity smsEntity = new SmsEntity();
        if(StringUtil.isBlank(param.get(PHONE))||StringUtil.isBlank(param.get(SMS_CODE))){
            logger.info("手机号：【{}】,短信模板：【{}】",param.get(PHONE),param.get(SMS_CODE));
            return "{'Code':'failed','Message':'手机号或者短信模板为空'}";
        }
        smsEntity.setPhoneNumbers(param.get(PHONE));
        smsEntity.setSmsCode(param.get(SMS_CODE));
        param.remove(PHONE);
        smsEntity.setParam(param);
        logger.info("调用下行短信，短信模板：{}，目标：{}，参数：{}",smsEntity.getSmsCode(),Base64JDK.encode(smsEntity.getPhoneNumbers()),smsEntity.getParam());
        return sendSms(smsEntity);
    }
}
